package com.example.taobaounion.ui.custom;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatImageView;

import com.example.taobaounion.R;

public class LoadingView extends AppCompatImageView {
    //旋转角度
    private float mDegrees=0;
    //是否需要旋转
    private boolean mNeedRotate=true;
    public LoadingView(Context context) {
        this(context,null);
    }

    public LoadingView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public LoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setImageResource(R.mipmap.loading);
    }

    //onAttachedToWindow()在onResume()之后运行，onDetachedFromWindow()则在onDestory()之后才会调用。
    //View附着到window上进行回调
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        mNeedRotate=true;
        startRotate();
    }

    private void startRotate() {
        post(new Runnable() {
            @Override
            public void run() {
                mDegrees+=10;
                if(mDegrees>=360){
                    mDegrees=0;
                }
                invalidate();//invalidate()方法用于重新触发一次View的绘制流程。也就是执行onDraw方法
                //LogUtils.d(LoadingView.this,"loading");
                //判断是否需要继续旋转
                //如果不可见，或者已经DetachedFromWindow就不可转动了
                if(getVisibility()!= VISIBLE&&!mNeedRotate){
                    removeCallbacks(this);
                }else {
                    postDelayed(this,100);
                }
            }
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopRotate();
    }

    private void stopRotate() {
        mNeedRotate=false;
    }

    //让图片转动起来
    @Override
    protected void onDraw(Canvas canvas) {
        //三个参数分别为旋转角度，x，y为中心转
        canvas.rotate(mDegrees,getWidth()/2,getHeight()/2);
        super.onDraw(canvas);
    }
}
